<template>
    <div class="product-eidt" style="max-height: 600px;">
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="选择产品">
                <div class="produccts">
                    <product
                            @selectProductItem="selectProductItem"
                            :products="form&&form.products"
                            v-for="product in products" :key="product.id" :product="product"></product>
                </div>

            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>

    import {createProp} from "../util/util";
    import jquery from 'jquery'
    import {findParentComponent} from "../util/findComponent";

    export default {
        props: {
            item: createProp([Object])
        },
        components: {
            product: () => import('./product-edit-item.vue')
        },
        data() {
            return {
                products: [],
                form: {
                    products: [],
                    layout: 'c2',
                },

            }
        },
        mounted() {
            if (this.item && this.item.props) {
                this.form.products = JSON.parse(JSON.stringify(this.item.props.products))
                this.form.layout = this.item.props.layout
            }

            this.getProducts()
        },
        methods: {
            getProducts() {
                jquery.get('http://www.liumingtai.com:7001/api/wx/products').then(res => {
                    var products = res.data.map(item => {
                        item.image = item.coverImage
                        return item
                    })
                    this.products = products
                })
            },
            selectProductItem(product) {
                if (this.form && this.form.products && this.form.products.length === 0) {
                    this.form.products.push(product)
                    return false
                }
                var index = this.form && this.form.products && this.form.products && this.form.products.findIndex(_product => _product.id === product.id)
                if (index >= 0) {
                    this.form.products.splice(index, 1)
                } else {
                   this.form.products.push(product)
                }
            },

            onSubmit() {
                var parent = findParentComponent(this, 'editAllParent')
                var index = parent.resultList.findIndex(item => item.id === this.item.id)
                parent.resultList[index].props.products = JSON.parse(JSON.stringify(this.form.products))
            }
        }
    }
</script>
<style lang="scss" scoped>
    .produccts {

        flex-wrap: wrap;
        display: flex;


    }


</style>
